import {message} from "antd";
import axios, {AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig} from "axios";

// 业务状态码
export const SuccessCode = 200
const LoginExpired = 10100013

// 基础返回结构
interface BaseResp {
    code: number
    msg: string
    data: never
}

// 发起请求方法
export const request = async <T = never>(
    config: AxiosRequestConfig
): Promise<T> => {
    try {
        const response = await instance(config);
        const body: BaseResp = response.data;
        const {code} = body;
        // 业务码处理
        if (code != SuccessCode) {
            switch (code) {
                case LoginExpired:
                    message.error("登录过期，请重新登录！！！")
                    window.location.pathname = '/login';
            }
        }
        return body as T;
    } catch (err) {
        if (axios.isAxiosError(err)) {
            message.error(`${(err as AxiosError).message}`);
        }
        // @ts-ignore
        console.error(`${err.request.responseURL} 接口请求失败: `, message);
        throw err;
    }
};

// Axios 实例
const instance = axios.create({
    timeout: 1000 * 60 * 60, // 10s timeout
    headers: {'X-Custom-Header': 'foobar'},
});

// 请求前处理
instance.interceptors.request.use((
    config: InternalAxiosRequestConfig<unknown>
) => {
    // 设置token
    config.headers['token'] = window.localStorage.getItem('token');
    return config
})

// 请求后处理
instance.interceptors.response.use(
    (response) => {
        return response;
    },
    (error: AxiosError) => {
        if (error.request.status == 401 && window.location.pathname != '/login') {
            window.location.pathname = '/login';
        }
        return Promise.reject(error);
    })

